package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.model.push.AutoPushMsg;
import com.iqiyi.pps.epg.core.model.push.EpgPlayPlatformTypeEnum;
import com.iqiyi.pps.epg.core.model.push.PassportAgentTypeEnum;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.service.push.AutoPushMsgService;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import com.iqiyi.pps.epg.web.service.passport.HttpPassportService;
import com.iqiyi.pps.epg.web.thread.AutoPushToDevicesThread;
import com.iqiyi.pps.epg.web.thread.SaveAutoPushToDevicesThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Deprecated
public class AutoProductPushMsgTrigger {
    private static Logger logger = LoggerFactory.getLogger(AutoProductPushMsgTrigger.class);

    private static final String PREPARE_EPISODE_LATE_TIME = Configuration.getString("push.prepare.episode.late.time");        //预备获取节目延迟时间（分钟）
    private static final String PREPARE_EPISODE_TIME = Configuration.getString("push.prepare.episode.time");             //预备获取节目时间范围(分钟)

    private static final int NTHREADES = 10;
    private static final int SAVE_PUSHDATA_BATCH_MAX = 100;

    @Autowired
    private ProgramService programService;
    @Autowired
    private AutoPushMsgService autoPushMsgService;

    public void task() {
        logger.info("[AutoProductPushMsgTrigger][start]");
        long taskStartTime = System.currentTimeMillis();
        try {
            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, Integer.valueOf(PREPARE_EPISODE_LATE_TIME));
            Long startTime = calendar.getTimeInMillis();
            calendar.add(Calendar.MINUTE, Integer.valueOf(PREPARE_EPISODE_TIME));
            Long endTime = calendar.getTimeInMillis();
            List<ProgramData> programDataList = programService.findSubscribeQuery(startTime, endTime);
            logger.info("[AutoProductPushMsgTrigger][programService.findSubscribeQuery(startTime, endTime)]][cost={}]", System.currentTimeMillis() - taskStartTime);
            ExecutorService exec = Executors.newFixedThreadPool(NTHREADES);
            if (programDataList != null && programDataList.size() > 0) {
                for (ProgramData programData : programDataList) {
                    Long episodeQipuId = programData.getQipuId();
                    Long episodeId = programData.getId();
                    int bossStatus = programData.getFreeStatus();
                    long noticeStartTime = programData.getNoticeStartTime().getTime();
                    // 已经在分发中，则不处理
                    boolean isExist = autoPushMsgService.findEffective(episodeId, new Date(noticeStartTime - 25 * 60 * 1000));
                    if (isExist) {
                        continue;
                    }
                    int page = 1;
                    List<AutoPushMsg> autoPushMsgs = new ArrayList<AutoPushMsg>();
                    while (true) {
                        long beginGetDeviceIdTime = System.currentTimeMillis();
                        Map<Integer, String> responseMap = HttpPassportService.getDeviceId(episodeQipuId, page);
                        logger.info("[endGetDeviceIdTime][cost={}]", System.currentTimeMillis() - beginGetDeviceIdTime);
                        if (responseMap == null || responseMap.size() <= 0) {
                            break;
                        }
                        // 获取下一页页号
                        Integer nextPage = Integer.parseInt(responseMap.get(-1));
                        responseMap.remove(-1);
                        int deviceLen = responseMap.size();
                        if (deviceLen > 0) {
                            // 整理订阅deviceId数据
                            Set<Integer> keySet = responseMap.keySet();
                            for (Iterator<Integer> it = keySet.iterator(); it.hasNext();) {
                                int index = it.next();
                                String[] str = responseMap.get(index).split(",");
                                Integer passportAgentTypeId = Integer.parseInt(str[0]);

                                String deviceId = str[1];
                                PassportAgentTypeEnum passportAgentTypeEnum = PassportAgentTypeEnum.valueOf(passportAgentTypeId);
                                if (passportAgentTypeEnum == PassportAgentTypeEnum.OTHER) {
                                    continue;
                                }
                                int epgPlayPlatform = EpgPlayPlatformTypeEnum.convert(PassportAgentTypeEnum.valueOf(passportAgentTypeId)).getPlayPlatformId();
                                int platformType = 0;
                                int appId = 0;
                                switch (EpgPlayPlatformTypeEnum.valueOf(epgPlayPlatform)) {
                                    case PPSANDRIODPAD:
                                    case PPSANDRIODPHONE:
                                        platformType = 21;
                                        appId = 1010;
                                        break;
                                    case PPSIOSIPAD:
                                    case PPSIOSIPHONE:
                                        platformType = 20;
                                        appId = 1010;
                                        break;
                                    case QIYIIOSIPHONE:
                                    case QIYIIOSIPAD:
                                        platformType = 20;
                                        appId = 1000;
                                        break;
                                    case QIYIANDRIODPHONE:
                                    case QIYIANDRIODPAD:
                                        platformType = 21;
                                        appId = 1000;
                                        break;
                                }
                                Timestamp pushTime = null;
                                if (platformType == 20) {
                                    long iosPushTime = noticeStartTime - AutoPushMsg.IOS_PUSH_TIME;
                                    pushTime = new Timestamp(iosPushTime);
                                } else if (platformType == 21) {
                                    long androidPushTime = noticeStartTime - AutoPushMsg.ANDRIOD_PUSH_TIME;
                                    pushTime = new Timestamp(androidPushTime);
                                }
                                // 设置ios和andriod push任务数据
                                AutoPushMsg saveAutoPushMsg = new AutoPushMsg();
                                saveAutoPushMsg.setEpisodeId(episodeId);
                                saveAutoPushMsg.setDeviceId(deviceId);
                                saveAutoPushMsg.setPassportAgentType(passportAgentTypeId);
                                saveAutoPushMsg.setPlatformType(platformType);
                                saveAutoPushMsg.setAppId(appId);
                                saveAutoPushMsg.setEpgPlayPlatform(epgPlayPlatform);
                                saveAutoPushMsg.setPushTime(pushTime);
                                saveAutoPushMsg.setPushStatus(0);
                                autoPushMsgs.add(saveAutoPushMsg);

                                //批量持久化推送任务数据
                                if (autoPushMsgs.size() >= SAVE_PUSHDATA_BATCH_MAX || !it.hasNext()) {
                                    exec.execute(new SaveAutoPushToDevicesThread(autoPushMsgs));
                                    autoPushMsgs = new ArrayList<AutoPushMsg>();
                                }
                            }
                            logger.info("[AutoProductPushMsgTrigger][saveList][cost={}]", System.currentTimeMillis() - taskStartTime);

                        }
                        if (nextPage <= 0) {
                            break;
                        } else {
                            page = nextPage;
                        }
                    }
                }
                logger.info("[AutoProductPushMsgTrigger][for循环结束][cost={}]", System.currentTimeMillis() - taskStartTime);
            }
        } catch (Exception e) {
            logger.error("[AutoProductPushMsgTrigger][error]{}", e);
        } finally {
            logger.info("[AutoProductPushMsgTrigger][end]");
        }
    }
}